#!/bin/bash
#!/bin/bash
scriptWorkd=$(cd "$(dirname $0)";pwd)

### ========= 全局变量 ===========
### ==============================

### ========= 前置文件 ===========
if [[ -f ${HOME}/bin/basic_func.sh ]];then  ### 存在才载入
    source ${HOME}/bin/basic_func.sh
elif [[ -f ${scriptWorkd}/../bin/basic_func.sh ]];then
    source ${scriptWorkd}/../bin/basic_func.sh
elif [[ -f ./bin/basic_func.sh ]];then
    source ./bin/basic_func.sh
fi
### ==============================


function main() {
set -e
    ## 开始信息
    echo -e "${blue4}\n$(basename $0)\n${normal}"

    sysType=$(awk -F= '/^ID=/{print $2}' /etc/os-release)
    sysVer=$(awk -F= '/^VERSION_ID=/{print $2}' /etc/os-release)
    sysVer=${sysVer#\"}
    sysVer=${sysVer%\"}
    userConfirm "System Type is ${sysType} ${green1}${sysVer}${normal}, is it RIGHT" y

    ## Ubuntu 24.00开始apt源文件执行DEB822标准
    if version_lt ${sysVer} 24.00; then
        echo -e "\n${hintStrProcessing}SourceFile is 'sources.list'\n"
        filename="/etc/apt/sources.list"
        if [[ ! -f ${filename}.bak ]]; then
            sudo cp ${filename} ${filename}.bak
        fi

        ## 启用Regex的sed
        sudo sed -r -i "s#http?://.*/#https://mirrors.tuna.tsinghua.edu.cn/${systemType}/#g" ${filename}
        cat ${filename} | grep tsinghua
    elif version_ge ${sysVer} 24.00; then
        echo -e "\n${hintStrProcessing}SourceFile is 'sources.list.d/ubuntu.sources'\n"
        filename="/etc/apt/sources.list.d/ubuntu.sources"
        if [[ ! -f ${filename}.bak ]]; then
            sudo cp ${filename} ${filename}.bak
        fi
        ## 启用Regex的sed
        sudo sed -r -i "s#http://archive.ubuntu.com#https://mirrors.tuna.tsinghua.edu.cn#" ${filename}
        cat ${filename} | grep tsinghua
    fi

    # exit 2  #debug
    

    ## 改ppa的源
    if [[ -e /etc/apt/source.list.d/ubuntu-toolchain-r-ubuntu-test-focal.list ]];then
        sudo sed -i "s/ppa.launchpad.net/launchpad.proxy.ustclug.org/g" /etc/apt/source.list.d/ubuntu-toolchain-r-ubuntu-test-focal.list
    fi
    echo -e "\n${hintStrOK} Apt Sources updated"
    echo -e "${hintStrOK} Apt源更换成功\n"

    ## 结束信息
    echo -e "${green4}\n$(basename $0)\n${normal}"
}
main $@


